import { NestFactory } from "@nestjs/core";
import { GatewayModule } from "./gateway.module";
import { MicroserviceOptions, Transport } from "@nestjs/microservices";
import { configuration } from "../../../config/config";
import { DocumentBuilder, SwaggerModule } from "@nestjs/swagger";
import { INestApplication } from "@nestjs/common";
import { Logger } from "nestjs-pino";
import { ProxyService } from "./proxy/proxy.service";
let app: INestApplication<any>;

async function bootstrap() {
  app = await NestFactory.create(GatewayModule, { bufferLogs: true });
  const proxyService = app.get(ProxyService); // 获取 ProxyService 的实例
  proxyService.setupProxy(app); // 调用 setupProxy 方法，传入 app 实例
  startOpenApi();

  const logger:Logger = app.get(Logger)
  logger.log("gateway的配置信息为：",configuration.gateway)
  await Promise.all([
    app.listen(configuration.gateway.http_port), // 启动 HTTP 服务

    app.connectMicroservice<MicroserviceOptions>({
      transport: Transport.NATS,
      options: {
        servers: configuration.natsServer,
      },
    }),
  ]);

  // 启动所有微服务
  await app.startAllMicroservices();
  console.log(
    "Gateway is running on http port " + configuration.gateway.http_port,
    "nats start",
    "websocket port:",
    configuration.gateway.socket_io_port,
  );
}

async function init() {
  await bootstrap();
}

init();

function startOpenApi() {
  const config = new DocumentBuilder()
    .setTitle("Gateway api")
    .setDescription("Gateway api")
    .setVersion(configuration.soft_version)
    .build();
  const document = SwaggerModule.createDocument(app, config);
  SwaggerModule.setup("api", app, document);
}
